<template>
  <div class="outer" v-loading="isLoading">
    <div class="inner">
      <el-card shadow="never" style="margin-bottom: 12px">
        <user-info />
      </el-card>
      <div style="font-size: 13px; color: #999; padding: 12px 12px 6px 12px">
        复训概要
      </div>
      <el-card shadow="never" style="margin-bottom: 12px; padding-bottom: 12px">
        <!-- <div slot="header">概要</div> -->
        <el-form label-width="75px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="年度：">
                <el-select
                  v-model="year"
                  size="small"
                  style="width: calc(100% - 24px)"
                  @change="getRecords"
                >
                  <el-option
                    v-for="item in yearList"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总学时：">
                <span>{{ totalHours }}</span>
                <span style="margin-left: 3px; font-size: 10px; color: #aaa"
                  >学时</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="未通过：">
                <span>{{ failedHours }}</span>
                <span style="margin-left: 3px; font-size: 10px; color: #aaa"
                  >学时</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="已复训：">
                <span>{{ annualHours }}</span>
                <span style="margin-left: 3px; font-size: 10px; color: #aaa"
                  >学时</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="待填写：">
                <span>{{ needFilling }}</span>
                <span style="margin-left: 3px; font-size: 10px; color: #aaa"
                  >记录</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="percentage"
                :status="percentage == 100 ? 'success' : null"
              ></el-progress>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <div style="font-size: 13px; color: #999; padding: 12px 12px 6px 12px">
        待填写的记录
      </div>
      <el-card shadow="never" style="margin-bottom: 12px">
        <el-table :data="recordsUnfilled" :show-header="false">
          <el-table-column>
            <template slot-scope="scope">
              <!-- <pre>{{scope.row}}</pre> -->
              <div style="margin-bottom: 6px">
                <span>{{ scope.row.title }}</span>
              </div>
              <div style="display: flex; align-items: center">
                <el-tag
                  size="mini"
                  :type="scope.row.pass == '是' ? 'success' : 'danger'"
                  style="margin-right: 6px"
                  >{{ scope.row.pass == "是" ? "通过" : "不通过" }}</el-tag
                >
                <el-tag size="mini" type="info" style="margin-right: 6px">{{
                  scope.row.coachName
                }}</el-tag>
                <!-- <el-tag
                size="mini"
                type="info"
                style="margin-right:6px"
              >{{scope.row.year}}年度</el-tag> -->
                <el-tag size="mini" type="info" style="margin-right: 6px">{{
                  dateFormat("M月d日", new Date(scope.row.trainingDate))
                }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="60px" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                circle
                icon="el-icon-edit"
                @click="handleEditorOpen(scope.$index)"
                style="margin: 0"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div style="font-size: 13px; color: #999; padding: 12px 12px 6px 12px">
        已完成的记录
      </div>
      <el-card shadow="never" style="margin-bottom: 12px">
        <div>
          <el-collapse accordion>
            <el-collapse-item
              v-for="(item, index) in recordsFinished"
              :key="index"
            >
              <template slot="title">
                <span>{{ item.title }}</span>
                <i
                  :class="
                    item.pass == '是' ? 'el-icon-success' : 'el-icon-warning'
                  "
                  :style="{
                    color: item.pass == '是' ? '#409EFF' : '#F56C6C',
                    paddingTop: '4px',
                  }"
                ></i>
              </template>
              <div>
                <el-alert
                  :title="item.pass == '是' ? '合格' : '不合格'"
                  :type="item.pass == '是' ? 'success' : 'error'"
                  :description="
                    item.pass == '否'
                      ? '需加练' +
                        item.failedSubjects.length +
                        '个科目：' +
                        item.failedSubjects.join('、')
                      : '无需加练'
                  "
                  show-icon
                  :closable="false"
                  style="margin-bottom: 12px"
                >
                </el-alert>
                <el-tag
                  type="info"
                  style="width: 100%; margin-bottom: 6px; border: none"
                >
                  <el-row>
                    <el-col :span="8">
                      <p><b>教员：</b>{{ item.coachName }}</p>
                    </el-col>
                    <el-col :span="10">
                      <p><b>日期：</b>{{ item.trainingDate }}</p>
                    </el-col>
                    <el-col :span="6">
                      <p><b>学时：</b>{{ item.hours }}</p>
                    </el-col>
                    <el-col :span="24">
                      <p><b>科目：</b>{{ item.subjects.join("、") }}。</p>
                    </el-col>
                    <!-- <el-col :span="12">
                    <p><b>创建：</b>{{item.commitTime}}</p>
                  </el-col>
                  <el-col :span="12">
                    <p><b>更新：</b>{{item.updateTime}}</p>
                  </el-col> -->
                  </el-row>
                </el-tag>
                <el-tag
                  type="info"
                  style="width: 100%; margin-bottom: 12px; border: none"
                >
                  <p v-for="item in item.evaluations" :key="item.title">
                    <b>{{ item.title }}：</b>
                    <el-rate
                      v-model="item.value"
                      disabled
                      style="display: inline-block; margin-left: 8px"
                    >
                    </el-rate>
                    <span style="padding-left: 12px">{{
                      ["E", "D", "C", "B", "A"][item.value - 1]
                    }}</span>
                  </p>
                </el-tag>
                <el-tag
                  type="info"
                  style="width: 100%; margin-bottom: 12px; border: none"
                >
                  <p
                    v-for="(item, index) in item.subjectsComments"
                    :key="index"
                  >
                    <b>{{ item.subject }}：</b>
                    {{ item.comments.join("，") }}
                    {{ item.commentPlus == "" ? "" : "，" }}
                    {{ item.commentPlus }}；
                  </p>
                  <p v-if="item.coachComments.length > 0">
                    <b>其他方面：</b>{{ item.coachComments }}。
                  </p>
                </el-tag>
                <el-tag
                  type="info"
                  style="width: 100%; margin-bottom: 24px; border: none"
                >
                  <p><b>您的自评：</b>{{ item.traineeComments }}</p>
                </el-tag>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-card>
      <el-dialog
        title="完成您的复训记录"
        :visible.sync="editorVisible"
        @close="handleEditorClose"
        destroy-on-close
        :fullscreen="screenWidth > 450 ? false : true"
        :width="screenWidth > 450 ? dialogWidth : null"
        :close-on-click-modal="false"
      >
        <div v-if="editorVisible" v-loading="isLoading">
          <el-alert
            :title="formData.title"
            type="info"
            :description="formData.subjects.join('、')"
            :closable="false"
            style="margin-bottom: 12px"
          >
          </el-alert>
          <div>
            <el-alert
              title="需要删除该记录吗？"
              type="error"
              :closable="false"
              style="margin-bottom: 12px"
            >
              <div>
                如果此记录有误，请点击下方按钮进行删除。此操作不可复原。
              </div>
              <div style="padding: 8px 0">
                <el-button type="danger" size="mini" @click="handleDelete"
                  >删除记录<b>&nbsp;No.{{ formData.number }}</b></el-button
                >
              </div>
            </el-alert>
          </div>
          <div style="border-bottom: 1px solid #e6e6e6; padding-top: 12px">
            <div style="font-size: 16px; font-weight: bold; padding: 6px 0">
              <i class="el-icon-info"></i>
              <span style="padding-left: 8px">基本信息</span>
            </div>
            <el-form label-width="100px">
              <el-row>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="部门：">
                    <el-select
                      v-model="formData.traineeDepartment"
                      size="small"
                      style="width: calc(100% - 24px)"
                    >
                      <el-option
                        v-for="item in userAttribs.department"
                        :key="item"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="科室：">
                    <el-select
                      v-model="formData.traineeOffice"
                      size="small"
                      style="width: calc(100% - 24px)"
                    >
                      <el-option
                        v-for="item in userAttribs.office"
                        :key="item"
                        :label="item"
                        :value="item"
                      ></el-option>
                      <!-- <el-option
                      label="无"
                      value="-"
                    ></el-option> -->
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="班组：">
                    <el-select
                      v-model="formData.traineeGroup"
                      size="small"
                      style="width: calc(100% - 24px)"
                    >
                      <el-option
                        v-for="item in userAttribs.group"
                        :key="item"
                        :label="item"
                        :value="item"
                      ></el-option>
                      <!-- <el-option
                      label="无"
                      value="-"
                    ></el-option> -->
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="职务：">
                    <el-select
                      v-model="formData.traineePost"
                      size="small"
                      style="width: calc(100% - 24px)"
                    >
                      <el-option
                        v-for="item in userAttribs.post"
                        :key="item"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="管制等级：">
                    <el-select
                      v-model="formData.traineeGrade"
                      size="small"
                      style="width: calc(100% - 24px)"
                    >
                      <el-option
                        v-for="item in userAttribs.grade"
                        :key="item"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="执照类型：">
                    <el-select
                      v-model="formData.traineeLicences"
                      multiple
                      size="small"
                      style="width: calc(100% - 24px)"
                      placeholder="请选择（可多选）"
                    >
                      <el-option
                        v-for="item in userAttribs.licences"
                        :key="item"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12"></el-col>
                <el-col :xs="24" :sm="12"></el-col>
              </el-row>
            </el-form>
          </div>
          <div style="border-bottom: 1px solid #e6e6e6; padding-top: 12px">
            <div style="font-size: 16px; font-weight: bold; padding: 6px 0">
              <i class="el-icon-s-comment"></i>
              <span style="padding-left: 8px">科目自评</span>
            </div>
            <el-input
              :autosize="false"
              :rows="4"
              v-model="formData.traineeComments"
              type="textarea"
              placeholder="请输入科目自我评定内容（必填）"
              style="margin-bottom: 24px; width: 100%"
            ></el-input>
          </div>
          <div style="border-bottom: 1px solid #e6e6e6; padding-top: 12px">
            <!-- <div style="font-size:16px;font-weight:bold;padding:6px 0">
            <i class="el-icon-s-comment"></i>
            <span style="padding-left:8px">教员评定</span>
          </div> -->
            <el-alert
              :title="formData.pass == '是' ? '合格' : '不合格'"
              :type="formData.pass == '是' ? 'success' : 'error'"
              :description="
                formData.pass == '否'
                  ? '需加练' +
                    formData.failedSubjects.length +
                    '个科目：' +
                    formData.failedSubjects.join('、')
                  : '无需加练'
              "
              show-icon
              :closable="false"
              style="margin-bottom: 12px"
            >
            </el-alert>
            <el-tag
              type="info"
              style="width: 100%; margin-bottom: 12px; border: none"
            >
              <p v-for="item in formData.evaluations" :key="item.title">
                <b>{{ item.title }}：</b>
                <el-rate
                  v-model="item.value"
                  disabled
                  style="display: inline-block; margin-left: 8px"
                >
                </el-rate>
                <span style="padding-left: 12px">{{
                  ["E", "D", "C", "B", "A"][item.value - 1]
                }}</span>
              </p>
            </el-tag>
            <el-tag
              type="info"
              style="width: 100%; margin-bottom: 24px; border: none"
            >
              <p
                v-for="(item, index) in formData.subjectsComments"
                :key="index"
              >
                <b>{{ item.subject }}：</b>
                {{ item.comments.join("，") }}
                {{
                  !item.commentPlus || item.commentPlus == ""
                    ? ""
                    : "，" + item.commentPlus
                }}
                ；
              </p>
              <p v-if="formData.coachComments.length > 0">
                <b>其他方面：</b>{{ formData.coachComments }}。
              </p>
            </el-tag>
          </div>
          <div style="padding: 24px 0; text-align: center">
            <el-button
              type="primary"
              size="small"
              style="width: 50%; max-width: 300px"
              @click="handleEditorSave"
              >提交</el-button
            >
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { format } from "@/utils/datetime.js";
import userInfo from "./userInfo.vue";
export default {
  name: "traineeView",
  components: {
    userInfo,
  },
  data() {
    return {
      year: new Date().getFullYear(),
      requiredHours: 24,
      totalRecords: [],
      recordsFinished: [],
      recordsUnfilled: [],
      editorVisible: false,
      editorTitle: "",
      formData: {},
      isLoading: false,
    };
  },
  computed: {
    yearList() {
      let year = new Date().getFullYear();
      return [year - 2, year - 1, year, year + 1];
    },
    percentage() {
      if (this.annualHours >= this.requiredHours) return 100;
      return Math.floor((this.annualHours / this.requiredHours) * 100);
    },
    dialogWidth() {
      return this.$store.getters.dialogWidth;
    },
    screenWidth() {
      return this.$store.state.screenSize.width;
    },
    userNumber() {
      return this.$store.getters.userNumber;
    },
    userName() {
      return this.$store.getters.userName;
    },
    recordsData() {
      return this.$store.state.traineeRecords;
    },
    userAttribs() {
      return this.$store.state.params.userAttribs;
    },
    totalHours() {
      // return this.totalRecords.length;
      // 统计已完成复训时长
      let sum = 0;
      if (this.totalRecords instanceof Array) {
        this.totalRecords.forEach((item) => {
          sum += item.hours;
        });
      }
      return sum;
    },
    annualHours() {
      // 统计已完成复训时长
      let sum = 0;
      if (this.totalRecords instanceof Array) {
        this.totalRecords.forEach((item) => {
          if (item.type == 1 && item.pass == "是") sum += item.hours;
        });
      }
      return sum;
    },
    failedHours() {
      let sum = 0;
      if (this.totalRecords instanceof Array) {
        this.totalRecords.forEach((item) => {
          if (item.pass == "否") sum += item.hours;
        });
      }
      return sum;
    },
    needFilling() {
      return this.recordsUnfilled.length;
    },
  },
  methods: {
    dateFormat: format,
    handleEditorOpen(idx) {
      this.editorVisible = true;
      this.editorTitle = "请填写个人信息和自评";
      this.formData = JSON.parse(JSON.stringify(this.recordsUnfilled[idx]));
    },
    handleEditorClose() {},
    handleEditorSave() {
      if (this.formData.traineeComments.length < 30) {
        this.$notify({
          title: "请填写自我评定",
          message: "科目自我评定内容不应少于30个字",
          type: "error",
        });
        return;
      }
      if (
        this.formData.traineeDepartment.length == 0 ||
        this.formData.traineeOffice.length == 0 ||
        this.formData.traineeGroup.length == 0 ||
        this.formData.traineePost.length == 0 ||
        this.formData.traineeGrade.length == 0 ||
        this.formData.traineeLicences.length == 0
      ) {
        this.$notify({
          title: "请填写基本信息的全部内容",
          message: "如无“科室”或“班组”请选择“其他”",
          type: "error",
        });
        return;
      }
      this.$store.dispatch("saveRecord", this.formData).then(() => {
        this.editorVisible = false;
        this.getRecords();
        this.$notify({
          title: "保存成功",
          message: "",
          type: "success",
        });
      });
    },
    getRecords() {
      this.recordsFinished = [];
      this.recordsUnfilled = [];
      this.$store
        .dispatch("getTraineeRecords", [
          { key: "year", value: this.year },
          { key: "traineeNumber", value: this.userNumber },
        ])
        .then((records) => {
          console.log("getRecords???", records);
          this.fetchRecords(records);
          this.totalRecords = records;
        });
    },
    fetchRecords(records) {
      for (let i = 0; i < records.length; i++) {
        if (
          records[i].traineeComments &&
          records[i].traineeComments.length > 0
        ) {
          this.recordsFinished.push(records[i]);
        } else {
          this.recordsUnfilled.push(records[i]);
        }
      }
    },
    handleDelete() {
      this.$confirm(
        "此操作将永久删除此条记录, 是否继续?",
        "删除记录 No." + this.formData.number,
        {
          confirmButtonText: "确定删除",
          cancelButtonText: "再考虑一下~",
          type: "warning",
        }
      )
        .then(() => {
          this.isLoading = true;
          this.axios
            .get("api/delete_record.php?id=" + this.formData.number)
            .then((response) => {
              // console.log(response);
              if (response.data.result) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getRecords();
                this.isLoading = false;
              } else {
                this.$message({
                  type: "warning",
                  message: "删除失败!",
                });
              }
              this.editorVisible = false;
            })
            .catch((error) => {
              console.error(error);
              this.$message({
                type: "error",
                message: "出错了!" + error.message,
              });
              this.editorVisible = false;
            });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
  },
  mounted() {
    this.getRecords();
  },
};
</script>

<style scoped>
.inner {
  width: 100%;
  max-width: 768px;
  padding: 0;
  margin: 0;
}

.outer {
  width: 100%;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
}
</style>
